﻿package models
import (
	"log"

)

type User struct{
	Id int32
	Username string
	Password string
}
func CountUsername(username string) int {
	var count int

	err := DBO.QueryRow("SELECT COUNT(*) FROM user where username=?",username).Scan(&count)
	if err != nil{
		return -1
	} 
	return count
}

func (u *User)UserValid() bool {
	var pw string
	row:=DBO.QueryRow("SELECT password FROM user where username=?",u.Username)
	err:=row.Scan(&pw)
	if err!=nil{

		panic(err)
	}
	if u.Password == pw {
		
		return true
	}else{
	
		return false
	}

}

func (u *User)CreateUser() (int64,error){
	stmt,err := DBO.Prepare("INSERT user SET username=?,password=?")
	if err != nil {
		return -1,err
	}
	res,err:=stmt.Exec(u.Username, u.Password)
	if err != nil {
		return -1,err
	}
	defer stmt.Close()
	id,err:=res.LastInsertId()
	if err != nil {
		return -1,err
	}
	return id, nil
}

func DeleteUser(username string) bool{
	if CountUsername(username)<1{
		return false
	}
	_ ,err := DBO.Exec("delete from user where username=?",username)
    if err != nil{
        log.Printf("delete failed,err:%v",err)
		return false
	}
	return true
}

func (u *User)UpdateUser() (int64,error){
	stmt,err := DBO.Prepare("UPDATE user SET password=? where username=?")
	if err != nil {
		return -1,err
	}
	res,err:=stmt.Exec(u.Password,u.Username)
	if err != nil {
		return -1,err
	}
	defer stmt.Close()
	rows,err:=res.RowsAffected()
	if err != nil {
		return -1,err
	}
	return rows, nil
}

func QueryUser(username string) (*User,error){
	var user User
	err := DBO.QueryRow("SELECT * from user where username=?",username).Scan(&user.Id,&user.Username,&user.Password)
	if err != nil {
		return &user,err
	}


	
	return &user, nil
}